#!/usr/bin/env python
"""Job Crawler in python

Produces reasanoble CSV output, helps by handling RSS, JSON and other
sorts of input, grabing emails.

Required: Python 2.5 or later
Recommended: Python 2.5 or later
Recommended: mechanize, feedparser
"""

__version__ = "0.1"# + "$Revision: 1.92 $"[11:15] + "-cvs"
__license__ = """Copyright (c) 2009, Yauhen Yakimovich, All rights reserved.
BSD-style License
==================

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

Neither the name of the contributors nor the names of their employers
may be used to endorse or promote products derived from this software
without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."""
__author__ = "Yauhen Yakimovich <http://ewger.desk.by/>"
__contributors__ = []
_debug = 0

# -Import------------------------------------------------------------------

import sys, os, re, datetime
# Import lib
sys.path.append('lib')

# -Functions---------------------------------------------------------------

def grabUrlWithBrowser(url):
	import mechanize
	br = Browser()
	br.set_handle_robots(None)
	br.open(url)
	response1 = br.response()
	assert br.viewing_html()
	#print br.title()
	#print response1.geturl()
	#print response1.info()  # headers
	return response1.read()  # body

def grabUrlWithUrllib2(url):
	import urllib2
	f = urllib2.urlopen(url)
	return f.read()	

def digEmails(url):
	body = grabUrlWithUrllib2(url)	
	mailsrch = re.compile(r'[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}')	
	match = mailsrch.findall(body)
	if (match is None) or (len(match) <= 0):
		#print "No emails found\n"
		return None
	# avoid dups
	res=list(set(match))
	return res

def processRss(url,keys=None,default=None):
	import feedparser
	from string import join
	if keys is None: keys =	['title','summary','link']
	if default is None: default=dict()

	res_with_emails = []
	res_without_emails = []
	rss = feedparser.parse(url)
	for item in rss['entries']:
		row = default.copy()
		for key in keys:
			row[key] = item[key].encode('ascii','ignore')
		row['emails'] = digEmails(row['link'])
		row['date'] = datetime.datetime.strptime(item['updated'], "%a, %d %B %Y %H:%M:%S %Z").strftime('%d.%m.%Y %H:%M')
		if row['emails'] is not None and len(row['emails']) > 0: 
			row['email'] = row['emails'][0]
			row['emails'] = join (row['emails'],' | ')
			res_with_emails.append(row)
		else:
			row['email'] = 'None'
			row['emails'] = 'None'
			res_without_emails.append(row)
		print "Processed %r ; title: %r\nemails: %r\n" % (row['date'],row['title'],row['emails'])
	return dict({'with_emails': res_with_emails, 'without_emails' : res_without_emails})

def writeCsvFile(file, table, csvdelim = ','):
	from string import join
	# check
	if table is None or  len(table)<=0:
		raise Exception("Error, table has no rows!")
		return
	# output
	csv = open(file, "w")
	# header
	header = "\"%s\"" % (join(table[0].keys(), "\""+csvdelim+"\""))
	csv.write(header+"\n")
	# rows
	for row in table:
		str = "\"%s\"" % (join(row.values(), "\""+csvdelim+"\""))
		csv.write(str+"\n")
	csv.close()	


